﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

class Program
{
    private const int HEARTBEAT_INTERVAL = 200; // 0.2 seconds in milliseconds

    private static void Main(string[] args)
    {
        StartServer();
    }

    private static void HandleClient(TcpClient client)
    {
        Console.WriteLine($"新连接: {client.Client.RemoteEndPoint}");
        try
        {
            NetworkStream stream = client.GetStream();
            byte[] buffer = new byte[1024];
            while (true)
            {
                int bytesRead = stream.Read(buffer, 0, buffer.Length);
                if (bytesRead == 0)
                {
                    break; // Client disconnected
                }

                string data = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                if (data.Trim() == "print")
                {
                    if (client.Client.RemoteEndPoint != null)
                    {
                        Console.WriteLine($"收到来自 {((IPEndPoint)client.Client.RemoteEndPoint).Address} 的打印请求");
                    }
                    else
                    {
                        Console.WriteLine("收到来自 未知地址 的打印请求");
                    }
                }

                byte[] heartbeatMessage = Encoding.ASCII.GetBytes("heartbeat");
                stream.Write(heartbeatMessage, 0, heartbeatMessage.Length);
                Console.WriteLine($"发送心跳包到 {client.Client.RemoteEndPoint}");
                Thread.Sleep(HEARTBEAT_INTERVAL);
            }
        }
        catch (Exception)
        {
            Console.WriteLine($"连接断开: {client.Client.RemoteEndPoint}");
        }
        finally
        {
            client.Close();
        }
    }

    private static void StartServer(string host = "127.0.0.1", int port = 12345)
    {
        TcpListener server = new TcpListener(System.Net.IPAddress.Parse(host), port);
        server.Start();
        Console.WriteLine($"服务器启动，监听 {host}:{port}");

        try
        {
            while (true)
            {
                TcpClient client = server.AcceptTcpClient();
                Thread clientThread = new Thread(() => HandleClient(client));
                clientThread.Start();
            }
        }
        catch (Exception)
        {
            Console.WriteLine("服务器关闭");
        }
        finally
        {
            server.Stop();
        }
    }
}
